#include "thread_handler.h"
#include "optDevice.h"
#include "registerDevice.h"
#include "my_link.h"

#include "replyOpt.h"

extern void registerDevice(int *id);
// extern void optDevice();
// extern void replyOpt();

int find_node(const void *in_dast, const void *in_str)
{
    data_type *dast = (data_type *)in_dast;
    data_type *str = (data_type *)in_str;

    if (dast->id[0] == str->id[0])
    {
        return 0;
    }

    return 1;
}

void *thread_handler(void *arg)
{
    pthread_detach(pthread_self());

    struct Pack pack;
    memset(&pack, 0, sizeof(pack));
    int cfd = *(int *)arg;

    printf("进入线程\n");

    while (1)
    {
        int ret = recv(cfd, &pack, sizeof(pack), 0);

        if (-1 == ret)
        {
            perror("recv");

            pthread_exit(NULL);
        }

        if (0 == ret)
        {
            fprintf(stderr, "cfd = %d client exit\n", cfd);
            // int tmp_cfd[2] = 0;
            data_type tmp_cfd = {0};
            tmp_cfd.id[0] = cfd;
            tmp_cfd.id[1] = 0;

            link_remove(H, &tmp_cfd, find_node);
            close(cfd);
            pthread_exit(NULL);
        }

        printf("switch pack.daType = %d\n", pack.dataType);

        switch (pack.dataType)
        {

        case 1:
        {
            printf("register!\n");

            int id[2] = {0};
            id[0] = pack.deviceId;
            id[1] = cfd;
            registerDevice(id); // 登陆注册 记录连接信息
        }

        break;

        case 2:
        {
            printf("send!%d\n%s\n", pack.deviceId, pack.opt);

            int cfd_dest = optDevice(pack.deviceId); // 通信 将信息发送给设备
            send(cfd_dest, pack.opt, strlen(pack.opt), 0);
        }

        break;

        case 3:
            printf("relpyOpt!\n");

            replyOpt(&pack); // 设备响应回复客户端
            break;
        }
    }

    printf("return!\n");
}
